import React, { useContext, useState } from "react";
import getConfig from "next/config";
import Link from "next/link";
import jwt from "jsonwebtoken";
import moment from "moment";
import styled, { keyframes, css } from "styled-components";
import { Check } from "@styled-icons/boxicons-regular/Check";
import { X } from "@styled-icons/boxicons-regular/X";
import { Plus } from "@styled-icons/boxicons-regular/Plus";
import { Search } from "@styled-icons/boxicons-regular/Search";
import { Filter } from "@styled-icons/boxicons-regular/Filter";
import { User } from "@styled-icons/boxicons-regular/User";
import { Time } from "@styled-icons/boxicons-regular/Time";
import SEO from "../../components/SEO";
import Box from "../../components/Box";
import Text from "../../components/Text";
import { withAuthServerSideProps } from "../../utils/withAuth";
import Button from "../../components/Button";
import Input from "../../components/Input";
import LocaleContext from "../../utils/LocaleContext";

// 动画效果
const fadeIn = keyframes`
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const scaleIn = keyframes`
  from {
    transform: scale(0.95);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
`;

const RequestCard = styled(Box)`
  background: ${(props) => props.theme.colors.sidebar};
  border-radius: 12px;
  min-height: 100px;
  padding: 24px 32px 20px 20px;
  margin-bottom: 20px;
  transition: box-shadow 0.2s, transform 0.2s;
  cursor: pointer;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: visible;
  &:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  &::before {
    content: "";
    position: absolute;
    top: 18px;
    left: 0;
    width: 5px;
    height: calc(100% - 36px);
    border-radius: 4px;
    background: ${(props) =>
      props.fulfilled
        ? props.theme.colors.success
        : props.theme.colors.primary};
    opacity: 0.9;
  }
`;

const StatusBadge = styled(Box)`
  position: absolute;
  top: 18px;
  right: 24px;
  padding: 4px 14px;
  border-radius: 16px;
  font-size: 0.9rem;
  font-weight: 500;
  background: ${(props) =>
    props.fulfilled ? props.theme.colors.success : props.theme.colors.primary};
  color: #fff;
  display: flex;
  align-items: center;
  gap: 6px;
  z-index: 2;
`;

const Title = styled(Text)`
  font-size: 1.25rem;
  font-weight: bold;
  margin-bottom: 8px;
  margin-left: 12px;
  color: ${(props) => props.theme.colors.text};
  word-break: break-all;
`;

const MetaRow = styled(Box)`
  display: flex;
  align-items: center;
  gap: 18px;
  margin-left: 12px;
  color: ${(props) => props.theme.colors.grey};
  font-size: 0.95rem;
`;

const SearchBar = styled(Box)`
  position: relative;
  margin-bottom: 24px;

  input {
    padding-left: 40px;
    border-radius: 12px;
    height: 48px;
    font-size: 1rem;
    border: 2px solid ${(props) => props.theme.colors.border};
    transition: all 0.3s ease;

    &:focus {
      border-color: ${(props) => props.theme.colors.primary};
      box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.1);
    }
  }
`;

const SearchIcon = styled(Search)`
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: ${(props) => props.theme.colors.grey};
  width: 20px;
  height: 20px;
`;

const FilterButton = styled(Button)`
  position: relative;
  padding: 12px 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
  }
`;

const CreateButton = styled(Button)`
  padding: 12px 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
  }
`;

const MetaInfo = styled(Box)`
  display: flex;
  align-items: center;
  gap: 8px;
  color: ${(props) => props.theme.colors.grey};
  font-size: 0.875rem;

  svg {
    width: 16px;
    height: 16px;
  }
`;

const Requests = ({ requests = [] }) => {
  const { getLocaleString } = useContext(LocaleContext);
  const [searchQuery, setSearchQuery] = useState("");
  const [filter, setFilter] = useState("all");
  const validRequests = Array.isArray(requests) ? requests : [];
  const filteredRequests = validRequests.filter((request) => {
    if (!request || !request.title) return false;
    const matchesSearch = request.title
      .toLowerCase()
      .includes(searchQuery.toLowerCase());
    const matchesFilter =
      filter === "all" ||
      (filter === "fulfilled" && request.fulfilledBy) ||
      (filter === "pending" && !request.fulfilledBy);
    return matchesSearch && matchesFilter;
  });
  return (
    <>
      <SEO title={getLocaleString("navRequests")} />
      <Box mb={6}>
        <Box
          display="flex"
          alignItems="center"
          justifyContent="space-between"
          mb={4}
        >
          <Text as="h1" fontSize={4} fontWeight="bold">
            {getLocaleString("navRequests")}
          </Text>
          <Box display="flex" gap={3}>
            <FilterButton variant="secondary">
              <Filter size={20} />
              {getLocaleString("filter")}
            </FilterButton>
            <Link href="/requests/new" passHref>
              <CreateButton as="a">
                <Plus size={20} />
                {getLocaleString("reqCreateNew")}
              </CreateButton>
            </Link>
          </Box>
        </Box>
        <SearchBar>
          <SearchIcon />
          <Input
            placeholder={getLocaleString("searchRequests")}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            width="100%"
          />
        </SearchBar>
        <Box>
          {filteredRequests.length > 0 ? (
            filteredRequests.map((request) => (
              <Link
                key={request._id}
                href={`/requests/${request.index}`}
                passHref
              >
                <RequestCard as="a" fulfilled={!!request.fulfilledBy}>
                  <StatusBadge fulfilled={!!request.fulfilledBy}>
                    {request.fulfilledBy ? (
                      <>
                        <Check size={16} />
                        {getLocaleString("reqFulfilled")}
                      </>
                    ) : (
                      <>
                        <X size={16} />
                        {getLocaleString("reqPending")}
                      </>
                    )}
                  </StatusBadge>
                  <Title>{request.title}</Title>
                  <MetaRow>
                    <MetaInfo>
                      <User size={16} />
                      {request.createdBy?.username ?? "deleted user"}
                    </MetaInfo>
                    <MetaInfo>
                      <Time size={16} />
                      {moment(request.created).format(
                        `${getLocaleString("indexTime")}`
                      )}
                    </MetaInfo>
                  </MetaRow>
                </RequestCard>
              </Link>
            ))
          ) : (
            <Box textAlign="center" py={5} color="grey">
              <Text fontSize={2}>
                {searchQuery
                  ? getLocaleString("noResultsFound")
                  : getLocaleString("noRequestsYet")}
              </Text>
            </Box>
          )}
        </Box>
      </Box>
    </>
  );
};

export const getServerSideProps = withAuthServerSideProps(
  async ({ token, fetchHeaders }) => {
    if (!token) return { props: {} };

    const {
      publicRuntimeConfig: { SQ_API_URL },
      serverRuntimeConfig: { SQ_JWT_SECRET },
    } = getConfig();

    const { role } = jwt.verify(token, SQ_JWT_SECRET);

    try {
      const requestsRes = await fetch(`${SQ_API_URL}/requests/page/0`, {
        headers: fetchHeaders,
      });
      if (
        requestsRes.status === 403 &&
        (await requestsRes.text()) === "User is banned"
      ) {
        throw "banned";
      }
      const requests = await requestsRes.json();

      return {
        props: { requests, userRole: role || "user" },
      };
    } catch (e) {
      if (e === "banned") throw "banned";
      return { props: {} };
    }
  }
);

export default Requests;
